<template>
    <view class="container">
        <NavBar title="材料入库" />
        <view class="steps">
            <uv-steps :current="actionIndex">
                <uv-steps-item title="添加入库单"></uv-steps-item>
                <uv-steps-item title="绑定材料"></uv-steps-item>
                <uv-steps-item title="入库成功"></uv-steps-item>
            </uv-steps>
        </view>
        <view class="form-content" v-if="actionIndex == 0">
            <!-- 入库编号 -->
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">入库编号</text>
                </view>
                <view class="form-input form-padding">
                    <!-- <uv-input class="input" placeholder="请输入内容" border="surround" v-model="formData.countNum" disabled
                        disabledColor></uv-input> -->
						{{ formData.countNum }}
                </view>
            </view>

            <!-- 计量周期 -->
            <!-- <view class="form-item">
                <view class="form-label">
                    <text class="label-text">计量周期</text>
                </view>
                <view class="form-input" @click="selectPeriod">
                    <text class="input-text" :class="{ placeholder: !formData.period }">{{ formData.period || '请选择'
                    }}</text>
                </view>
            </view> -->
            <!-- 入库时间 -->
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">入库时间</text>
                </view>
                <view class="form-input form-padding">
                    {{ formData.enterTime }}
                </view>
            </view>
            <!-- 供应商 -->
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">供应商</text>
                </view>
                <view class="form-input form-padding" @click="selectSupplier">
                    <!-- <text class="input-text" :class="{ placeholder: !formData.supplier }">{{ formData.supplier || '请选择'
                        }}</text> -->
						<!-- {{ formData.supplier || '请选择'}} -->
						<uv-text v-show="!formData.supplier" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
						<text v-show="formData.supplier">{{formData.supplier}}</text>
                </view>
            </view>
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">供应商合同</text>
                </view>
                <!-- <view class="form-input" @click="selectPeriodcontract">
                    <text class="input-text" :class="{ placeholder: !annexName }">{{ annexName || '请选择'
                        }}</text>
                </view> -->
                <uploadFile class="form-padding" ref="uploadFile" :max-count="1" @change="onUploadChange" :max-file-size="1024 * 1024 * 20"
                    :allowed-extensions="['ppt', 'txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx']"
                    @success="onUploadSuccess"></uploadFile>
            </view>
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">预计合同金额</text>
                </view>
                <view class="form-input">
                    <uv-input class="input" placeholder="请输入内容" border="surround" v-model="formData.contractPrice"
                        type="number"></uv-input>
                </view>
            </view>
            <view class="form-item">
                <view class="form-label">
                    <text class="label-text">附件</text>
                </view>
                <view class="form-item">
                    <view class="imgfile wrap__preview" v-show="imgFile.length!==0" v-for="(item,index) in imgFile" :key="index">
                    	<image  class="imgfile" :src="item" mode="scaleToFill"></image>
                    	<view class="deletable" @click="deletePic(index)">
                    		<uv-icon name="close" size="10px" color="#fff"></uv-icon>
                    	</view>
                    </view>
                    <view v-show="imgFile.length < 5" class="plus-icon" @click="chooseImage">
                        <uv-icon name="plus"></uv-icon>
                    </view>

                </view>
            </view>
        </view>
        <view class="materials-form" v-if="actionIndex === 1">
            <view class="selector">
                <view class="selector-title">
                    材料模板
                </view>
                <view class="selector-content" @click="showOutPicker = true">
                    请选择
                </view>
            </view>
            <view class="materials" v-if="showMaterials">
                <!-- <view class="materials-title">
                    选择材料
                </view> -->
                <scroll-view scroll-y class="materials-from">
                    <!-- <view class="materials-item" v-for="(i, index) in materialList" :key="i.id || index">

                        <view class="description">
                            <view>
                                <view class="materials-encoding">
                                    {{ i.label }}
                                </view>
                                <view class="description-content">
                                    {{ i.name }} | {{ i.specs }} | {{ i.unit }}
                                </view>
                            </view>
                            <view v-if="i.contract">
                                <view class="description-content">
                                    <text class="desc">{{ i.contract }}</text>|
                                    <text class="desc_cycle">{{ i.cycle }}</text>|
                                    <text class="">{{ i.lnum }}</text>|
                                    <text class="">{{ i.drawUnitPrice }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="from-use-input">
                            <uv-text type="primary" text="领用" size="10" @click="goToUse(i, index)"></uv-text>
                        </view>
                        <view class="from-price-input">
                            <uv-input class="from-price-input-input" placeholder="金额" border="surround"
                                v-model="i.unitPrice" shape="circle"></uv-input>
                            <uv-number-box v-model="i.num" @change="handleNumChange(i, index)" :min="0">
                                <template v-slot:minus>
                                    <view class="minus">
                                        <uv-icon name="minus" @click="isAdd = false" size="10">
                                        </uv-icon>
                                    </view>
                                </template>
                                <template v-slot:input>
                                    <text style="width: 50px;text-align: center;" class="input">
                                        {{ i.num }}
                                    </text>
                                </template>
                                <template v-slot:plus>
                                    <view class="plus">
                                        <uv-icon name="plus" @click="isAdd = true" color="#FFFFFF" size="10">
                                        </uv-icon>
                                    </view>
                                </template>
                            </uv-number-box>
                        </view>
                    </view> -->
					<view class="material-item" v-for="(i, index) in materialList" :key="i.id || index">
						<view class="delete-but" @click="deletebut(index,i)">
							删除
						</view>
						<view class="item-box">
							<view class="title">
								材料名称
							</view>
							<view class="content">
								 {{ i.name }}
							</view>
						</view>
						<view class="item-box">
							<view class="title">
								材料规格
							</view>
							<view class="content">
								{{ i.specs }}
							</view>
						</view>
						<view class="item-box">
							<view class="title">
								材料单位
							</view>
							<view class="content">
								{{ i.unit }}
							</view>
						</view>
						<view class="item-box">
							<view class="title">
								材料金额
							</view>
							<view class="content content-flex">
								  <uv-input placeholder="请输入金额" v-model="i.unitPrice" border="bottom" ></uv-input>
								  <uv-text text="元"></uv-text>
							</view>
						</view>
						<view class="item-box">
							<view class="title">
								材料数量
							</view>
							<view class="content content-flex">
								  <uv-input placeholder="请输入数量" v-model="i.num" border="bottom" ></uv-input>
								  <uv-text :text="i.unit"></uv-text>
							</view>
						</view>
						<uv-divider v-show="receive[i.id].isShow"></uv-divider>
						<view v-show="receive[i.id].isShow">
							<view class="item-box">
								<view class="title">
									施工合同
								</view>
								<view class="content" @click="selectcontract(i)">
									
									<uv-text v-show="!i.contract" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
									<text v-show="i.contract">{{i.contract}}</text>
								</view>
							</view>
							<view class="item-box">
								<view class="title">
									计量周期
								</view>
								<view class="content" @click="selectcycle(i)">
									
									<uv-text v-show="!i.cycle" suffixIcon="arrow-down-fill" iconStyle="font-size: 8px" text="请选择"></uv-text>
									<text v-show="i.cycle">{{i.cycle}}</text>
								</view>
							</view>
							<view class="item-box">
								<view class="title">
									领用数量
								</view>
								<view class="content content-flex">
									<uv-input placeholder="请输入领用数量" @blur='changeInput(i)' v-model="i.drawNum" border="bottom" ></uv-input>
									<uv-text :text="i.unit"></uv-text>
									<!-- <input class="content-input" v-model="i.lnum" @input="changeInput(i)"  type="number" placeholder="请输入领用数量" /> -->
									
								</view>
							</view>
							<view class="item-box">
								<view class="title">
									领用单价
								</view>
								<view class="content content-flex">
									<uv-input placeholder="请输入领用单价" v-model="i.drawUnitPrice " border="bottom" ></uv-input>
									<uv-text text="元"></uv-text>
								</view>
							</view>
							<view class="item-box accessory">
								<view class="title">
									附件
								</view>
								<view class="content content-flex">
									<!-- JSON.parse(uploadFileRes.data).annexUrl length-->
									<!-- <image v-show="imgListTwo[i.id].length !=0" v-for="item in imgListTwo[i.id]" class="imgfile" :src="item"></image> -->
									<view class="imgfile wrap__preview" v-show="imgListTwo[i.id].length !=0" v-for="(item,index) in imgListTwo[i.id]">
										<image  class="imgfile" :src="item" mode="scaleToFill"></image>
										<view class="deletable" @click="deletePicList(index,i.id)">
											<uv-icon name="close" size="10px" color="#fff"></uv-icon>
										</view>
									</view>
									<view v-show='imgListTwo[i.id].length < 5' class="plus-icon" @click="chooseImage(i)">
									    <uv-icon name="plus"></uv-icon>
									</view>
								</view>
							</view>
						</view>
						<view class="bottom-button">
							<view class="bottom-button-box">
								<view class="but" v-show="!receive[i.id].isShow" @click="goToUse(i, index)">
									领用
								</view>
								<view class="but" v-if="receive[i.id].isShow" @click="cancel(i, index)">
									取消领用
								</view>
							</view>
						</view>
					</view>
					<view class="empty">
						
					</view>
                </scroll-view>
            </view>
        </view>
        <view class="management" v-if="actionIndex === 2">
            <image class="succeed-img" src="/static/succeed-img.png" mode=""></image>
            <text class="reminder">材料入库成功</text>
            <view class="look-but but" @click="goToLook">
                查看入库单
            </view>
            <view class="continue-but but" @click="goToContinue">
                继续入库
            </view>
        </view>

        <view class="bottom-bar" v-show="actionIndex <= 1">
            <view class="next-button" @click="goToNextStep">
                <text class="button-text">下一步</text>
            </view>
        </view>
        <!-- 底部弹出层 -->
        <view v-if="showOutPicker" class="picker-container">
            <view class="picker-mask" @click="closeOutPicker"></view>
            <view class="picker-content">
                <view class="picker-header">
                    <text class="picker-cancel" @click="closeOutPicker">取消</text>
                    <text class="picker-title">选择模板</text>
                    <text class="picker-confirm" @click="confirmOut">确定</text>
                </view>
                <view class="form-head">
                    <view class="form-select">
                        选择
                    </view>
                    <view class="form-encoding">
                        编码
                    </view>
                    <view class="from-name">
                        名称
                    </view>
                    <view class="from-specification">
                        规格
                    </view>
                </view>

                <scroll-view scroll-y class="picker-list">
                    <view class="picker-item" v-for="(item, index) in outOptions" :key="item.id"
                        :class="{ 'from-double': index % 2 === 1 }">
                        <view class="form-select">
                            <checkbox :checked="selectedOutOption.includes(item.value)"
                                @click.stop="toggleOutOption(item)" />
                        </view>
                        <view class="form-encoding">{{ item.code }}</view>
                        <view class="from-name">{{ item.name }}</view>
                        <view class="from-specification">{{ item.specs }}</view>
                    </view>
                </scroll-view>
            </view>
        </view>
		<view v-if="isShowsupplier" class="picker-containers">
		  <view class="picker-masks" @click="closeOutPickersupplier()"></view>
		  <view class="picker-contents">
		    <view class="picker-headers">
		      <text class="picker-cancels" @click="closeOutPickersupplier()">取消</text>
		      <text class="picker-titles">选择供应商</text>
		      <text class="picker-confirms" @click="confirmOutsupplier()">确定</text>
		    </view>
		    <scroll-view scroll-y class="picker-lists">
		      <view  class="picker-items" v-for="(item, index) in supplierList"  :key="index" 
		            :class="{ 'selecteds': formData.supplierId === item.id }"
		            @click="selectOutOption(item)">
		        <text>{{ item.name }}</text>
		      </view>
			  <view class="black-boxs">
			  	
			  </view>
		    </scroll-view>
			
		  </view>
		</view>
        <!-- 领用弹出层组件 -->
        <use-picker ref="usePicker" :useIndexId="useIndexId" :materialList="materialList" :queryParams="queryParams"
            @confirmUse="confirmUse" />
		<!-- <uv-modal ref="modal"  title="删除" content='是否确定删除？' cancelText="再想想"
		    confirmText="确定"  align="center" confirmColor="#FF3B30" ancelColor="#165DFF"
		    @confirm="confirm" @cancel="cancel">
		</uv-modal> -->
		<uv-modal ref="modal" title="删除" content='确认删除吗' align="center" @confirm="confirm" @cancel="cancelDel" :showCancelButton="true"></uv-modal>
    </view>
</template>

<script>
import NavBar from '@/components/NavBar/index.vue'
import pickerCom from '@/components/pickerCom.vue'
import {
    getNewCodeByProjectId,
    getCyclemanagementList,
    getsupplier,
    getContractList,
    getMaterialProject,
    getmaterialEntryApp,
    queryAllByRelatedIdIdAndType,
	getSupplierqueryAll
} from '@/utils/app.js'
import usePicker from './use.vue'
import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
import { BASEURL } from '@/utils/request.js'
import uploadFile from '@/components/upload/index.vue'
export default {
    components: {
        NavBar,
        usePicker,
        uploadFile,
		pickerCom
    },
    data() {
        return {
            imgList: [],
            imgFile: [],
            tempFile: [],
			imgListTwo:{},
            maxNum: 5,
            attachmentUrl: '',
            annexName: '',
            actionIndex: 0,
            formData: {
                countNum: '',
                code: 'RK-000027',
                period: '',
                supplier: '',
                enterTime: ''
            },
            // 弹出框
            showOutPicker: false,
            outOptions: [],
            contractList: [],
            queryParams: {},
            meteringList: [],
            supplierList: [],
            materialList: [],
            showMaterials: false,
            selectedOutOption: [],
            formParams: {},
            formattedDate: '',
            formDataId: '',
            isAdd: true,
            useIndexId: 0,
			activeIndex:[],
			arrActive:[],
			isShow:false,
			deleteId:'',
			receive:{},
			outOptionsList:[],
			activeId:'',
			isShowsupplier:false,
        };
    },
    watch: {
        //监听materialList
        materialList: {
            handler(newVal) {
                if (!newVal.length) {
                    this.showMaterials = false;
                }
            },
            deep: true
        },
        'imgFile.length': function (newLength, oldLength) {
            this.maxNum = 5 - newLength
        },
		arrActive:{
			handler(newVal){
				console.log(this.outOptionsList,newVal);
				let arr = [...this.outOptionsList]
				newVal.forEach(item=>{
					arr = arr.filter(i=>i.id !== item)
					console.log('rss',arr);
					
				})
				this.outOptions = [...arr]
			},
			deep:true
		},
		actionIndex:{
			handler(newVal){
				if(newVal==1){
					this.imgFile = []
				}
			}
		}
    },
	computed:{
		// imgNum(i){
		// 	return this.imgListTwo[i.id].length
		// }
	},
    onLoad(options) {
        this.formData.enterTime = timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss')
        if (options.data) {
            try {
                const parsedData = JSON.parse(decodeURIComponent(options.data));
                if (parsedData) {

                    let data = {
                        projectId: parsedData.projectId
                    }
                    this.queryParams = parsedData;
                    this.queryParams.projectId = parsedData.projectId;
                    this.getNewCodeByProjectData(data)
                    this.getContractData(data)
                    this.getsupplierData({...data,supplierType:1});
                }
            } catch (error) {
                uni.showToast({
                    title: '数据解析失败',
                    icon: 'none'
                });
            }
        }

    },
    methods: {
		deletebut(i,e){
			console.log(111,this.$refs.modal);
			this.$refs.modal.open();
			this.deleteId = i
			this.activeId = e.id
			
			console.log(this.arrActive,e.id);
		},
		deletePic(index) {
			// console.log(event.name,this.fileList,this[`fileList${event.name}`]);
		    this.imgFile.splice(index, 1)
			this.imgList.splice(index, 1)
		},
		deletePicList(i,id){
			this.imgListTwo[id].splice(i,1)
		},
		confirm() {
			// console.log('点击确认按钮');
			this.materialList.splice(this.deleteId, 1);
			this.arrActive = this.arrActive.filter(item=>item != this.activeId)
			this.$refs.modal.close()
		},
		cancelDel(){
			this.$refs.modal.close()
		},
		changeInput(e){
			console.log(e);
			// console.log(e.lnum,e.num);
			if(Number(e.drawNum)>e.num){
				
				uni.showToast({
				    title: '领用数量不能大于库存数量',
				    icon: 'none'
				});
				this.materialList.forEach(item => {
				
				    if (item.id == e.id) {
				        item.drawNum = '';
				        
				    }
				});
				
			}
		},
        onUploadSuccess(files) {
            this.formData.annexName = files.name;
            this.formData.annexUrl = files.url;

        },
		selectcontract(i){
			console.log(this.materialList);
			const itemList = this.contractList.map(item => item.name)
			console.log(this.contractList,itemList);
			uni.showActionSheet({
			    itemList,
			    success: (res) => {
			        // 通过tapIndex反查id
			        const selected = this.contractList[res.tapIndex]
			        // this.formData.contract = selected.name
			        // this.formData.contractId = selected.id
					this.materialList.forEach(item => {
					
					    if (item.id == i.id) {
					        item.contract = selected.name;
					        item.type = selected.type;
					        item.contractId = selected.id;
					    }
					});
			    }
			});
		},
		selectcycle(i){
			const itemList = this.meteringList.map(item => item.name)
			console.log(this.contractList,itemList);
			uni.showActionSheet({
			    itemList,
			    success: (res) => {
			        // 通过tapIndex反查id
			        const selected = this.meteringList[res.tapIndex]
					this.materialList.forEach(item => {
					
					    if (item.id == i.id) {
					        item.cycle = selected.name;
					        item.cycleId = selected.id;
					    }
					});
			    }
			});
		},
        onUploadChange(files) {
            // files 是已上传成功的文件数组
            this.formData.attachmentUrl = files.map(f => f.serverUrl).join(',');
        },
        // 选择图片
        chooseImage(i) {
			if(this.actionIndex==1){
				this.imgFile = [...this.imgListTwo[i.id]]
			}
            const that = this
            uni.chooseImage({
                count: this.maxNum, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                success: async (res) => {
                    that.tempFile = [...res.tempFilePaths]
                    const token = uni.getStorageSync("token");
                    that.tempFile.forEach(item => {
                        // #ifdef APP-PLUS
                        if (item.split(':')[0] != 'file') {
                            let p = plus.io.convertLocalFileSystemURL(item);
                            that.imgFile.push('file://' + p)
                            uni.uploadFile({
                                url: `${BASEURL}/common/upload`,
                                filePath: 'file://' + p,
                                header: {
                                    'Authorization': token,
                                },
                                name: 'file',
                                success: (uploadFileRes) => {
									if(this.actionIndex==1){
										this.imgListTwo[i.id] = [...this.imgListTwo[i.id],JSON.parse(uploadFileRes.data).annexUrl]
										// this.imgListTwo.push(JSON.parse(uploadFileRes.data).annexUrl)
									}else{
										this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
									}
                                    // this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
                                    // 获取上传服务器的地址 
                                }
                            });
                        } else {
                            that.imgFile.push(item)
                            uni.uploadFile({
                                url: `${BASEURL}/common/upload`,
                                filePath: item,
                                header: {
                                    'Authorization': token,
                                },
                                name: 'file',
                                success: (uploadFileRes) => {
                                    // this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
                                    // 获取上传服务器的地址
									if(this.actionIndex==1){
										// this.materialList.forEach(item => {
										
										    this.imgListTwo[i.id] = [...this.imgListTwo[i.id],JSON.parse(uploadFileRes.data).annexUrl]
										// });
									}else{
										this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
									}
                                }
                            });
                        }
                        // #endif

                        // #ifdef H5
                        that.imgFile.push(item)

                        uni.uploadFile({
                            url: `${BASEURL}/common/upload`,
                            filePath: item,
                            header: {
                                'Authorization': token,
                            },
                            name: 'file',
                            success: (uploadFileRes) => {
                                // this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
								if(this.actionIndex==1){
									// this.materialList.forEach(item => {
										// if(Object.keys(this.imgListTwo).includes(i.id)){
											// if(!this.myObject[i.id]){
												// this.$set(this.imgListTwo, i.id, []);
											// }
											
										// }
									     this.imgListTwo[i.id] = [...this.imgListTwo[i.id],JSON.parse(uploadFileRes.data).annexUrl]
									// });
								}else{
									this.imgList.push(JSON.parse(uploadFileRes.data).annexUrl)
								}
                                // 获取上传服务器的地址
                            }
                        });
                        // #endif

                    })

                }
            });
        },
        onPullDownRefresh() {
            this.getNewCodeByProjectData({
                projectId: this.queryParams.projectId
            })
            this.getContractData({
                projectId: this.queryParams.projectId
            })
            this.getsupplierData({
                projectId: this.queryParams.projectId,
				supplierType:1
            })
        },
        getNewCodeByProjectData(data) {
            getNewCodeByProjectId(data).then(res => {
                this.formData.countNum = res.data;
            })
        },
        //周期
        getCyclemanagementData() {
            getCyclemanagementList(this.queryParams).then(res => {
                if (res.code == 200) {
                    this.meteringList = res.rows.map(item => ({
                        name: item.cycleName,
                        id: item.id
                    }))
                }
            })
        },
        goToUse(item, index) {
            this.useIndexId = item.id;

            if (!item.unitPrice) {
                uni.showToast({
                    title: '请先设置金额',
                    icon: 'none'
                });
                return;
            }

            this.formParams = {
                ...this.formParams,
                ...item,
            };
			// this.isShow = true
			this.receive[item.id].isShow = true
            // this.$refs.usePicker.openUsePicker(item);
        },
        //供应商
        getsupplierData(data) {
            getSupplierqueryAll(data).then(res => {
                if (res.code == 200) {
                    this.supplierList = res.data.map(item => ({
                        name: item.name,
                        id: item.id
                    }))
                }
            })
        },
        //合同
        getContractData(data) {
            // data.parentId = 0;
            getContractList(data).then(res => {
                if (res.code == 200) {
                    this.queryParams.contractId = res.rows[0].id;
					res.rows = res.rows.filter(item => item.parentId != 0);
					this.contractList = res.rows.map(item => ({
					    name: item.contractName,
					    id: item.id,
					    type: item.type,
					    projectId: data.projectId
					}));
                    this.getCyclemanagementData()
                }
            })
        },
        //供应商
        selectSupplier() {
			this.isShowsupplier = true
            // const itemList = this.supplierList.map(item => item.name)
            // uni.showActionSheet({
            //     itemList,
            //     success: (res) => {
            //         // 通过tapIndex反查id
            //         const selected = this.supplierList[res.tapIndex]
            //         this.formData.supplier = selected.name
            //         this.formData.supplierId = selected.id
            //     }
            // });
        },
        //周期
        selectPeriod() {
            const itemList = this.meteringList.map(item => item.name)
            uni.showActionSheet({
                itemList,
                success: (res) => {
                    const selected = this.meteringList[res.tapIndex];
                    this.formData.period = selected.name
                    this.formData.periodId = selected.id
                }
            });
        },
        selectPeriodcontract() {
            queryAllByRelatedIdIdAndType({ relatedId: this.formData.supplierId, type: 4 }).then(res => {
                this.contractList = res.data
                if (res.code == 200) {

                    const itemList = res.data.map(item => item.annexName)
                    uni.showActionSheet({
                        itemList,
                        success: (res) => {
                            const selected = this.contractList[res.tapIndex];
                            this.annexName = selected.annexName
                            this.formData.annexId = selected.id
                        }
                    });
                }

            })
        },
        //获取项目材料列表
        getMaterialProjectData(data) {
            getMaterialProject(data).then(res => {
                if (res && res.code == 200) {
                    this.outOptions = res.data
					this.outOptionsList = res.data
                }
            })
        },
        //确定
        confirmUse(data) {

            this.formParams = {
                ...data,
                ...this.formParams,
            }

            //将领用的数据根据useIndexId存入对应的materialList中
            this.materialList.forEach(item => {

                if (item.id == this.useIndexId) {
                    item.num = this.formParams.num;
                    item.drawUnitPrice = data.drawUnitPrice;
                    item.contract = data.contract;
                    item.cycle = data.cycle;
                    item.lnum = data.lnum;
                    item.type = data.type;
                    item.contractId = data.contractId;
                    item.cycleId = data.cycleId;
                }
            });

        },
		// 取消领用
		cancel(i){
			this.isShow = false
			this.receive[i.id].isShow = false
			console.log(i);
			this.materialList.forEach(item => {
				
			    if (item.id == i.id) {
			        item.drawUnitPrice = '';
			        item.contract = '';
			        item.cycle = '';
			        item.lnum = '';
			        item.type = '';
			        item.contractId = '';
			        item.cycleId = '';
			    }
			});
			console.log(this.materialList);
		},
        handleNumChange(i, index) {
            if (!this.isAdd) {
                // 如果数量为0，则删除该项
                if (i.num == 1) {
                    this.$set(this.materialList, index, null);
                    this.materialList.splice(index, 1);
                }
            }

        },
        //下一步
        goToNextStep() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const day = now.getDate();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            const seconds = now.getSeconds();
            this.formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            let newMaterialList = this.materialList.map(item => {
				console.log(item);
                let baseItem = {
                    ...item,
                    materialProjectId: this.formParams.id,
                    projectId: this.queryParams.projectId,
                    contractId: this.queryParams.contractId,
                    cycleId: this.formParams.cycleId,
                    createTime: this.formattedDate,
					annexe:this.imgListTwo[item.id].join(',')
                }

                // 只有当useIndexId与item.id相同时才赋值这些字段
                // if (item.id == this.useIndexId) {
                //     baseItem.drawNum = this.formParams.lnum;
                //     baseItem.drawUnitPrice = this.formParams.drawUnitPrice;
                //     baseItem.unitPrice = this.formParams.unitPrice;
                //     baseItem.type = this.formParams.type;
                // }

                return baseItem;
            })
            let dataParams = {
                clMaterialSingle: {
                    projectId: this.queryParams.projectId,
                    supplierId: this.formData.supplierId,
                    cycleId: this.formData.periodId,
                    code: this.formData.countNum,
                    enterTime: this.formData.enterTime,
                    annexId: this.formData.annexId,
                    attachmentUrl: this.imgList.join(','),
                    contractPrice: this.formData.contractPrice,
                    annexName: this.formData.annexName,
                    annexUrl: this.formData.annexUrl,
                },
                clMaterialSingleItems: this.materialList.map(item => ({
                    code: item.code,
                    name: item.name,
                    specs: item.specs,
                    unit: item.unit,
                    unitPrice: item.unitPrice,
                    num: item.num,
                })),
                clMaterialDraws: newMaterialList,
            };


            if (this.actionIndex == 0) {
                let data = {
                    projectId: this.queryParams.projectId
                }
                //若表单未填写，则提醒
                // if (!this.formData.period) {
                //     uni.showToast({
                //         title: '请填写周期',
                //         icon: 'none'
                //     });
                //     return;
                // }
                if (!this.formData.annexUrl) {
                    uni.showToast({
                        title: '请选择供应商合同',
                        icon: 'none'
                    });
                    return;
                }

                if (!this.formData.supplier) {
                    uni.showToast({
                        title: '请选择供应商',
                        icon: 'none'
                    });
                    return;
                }
				if (!this.formData.contractPrice) {
				    uni.showToast({
				        title: '请填写预计合同金额',
				        icon: 'none'
				    });
				    return;
				}
                this.getMaterialProjectData(data)
				
            }
            if (this.actionIndex == 1) {
                //若材料列表为空，则提醒
                if (this.materialList.length == 0) {
                    uni.showToast({
                        title: '请选择材料',
                        icon: 'none'
                    });
                    return;
                }

                //价格不能为空
                let isPriceEmpty = this.materialList.some(item => !item.unitPrice);
                if (isPriceEmpty) {
                    uni.showToast({
                        title: '请填写材料价格',
                        icon: 'none'
                    });
                    return;
                }
                getmaterialEntryApp(dataParams).then(res => {
                    if (res && res.code == 200) {

                        this.formDataId = res.data;
                        uni.showToast({
                            title: '入库成功',
                            icon: 'success'
                        });
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            }


            // 保存入库单信息，进入下一步（绑定材料）
            // uni.navigateTo({
            //   url: '/pages/material/add-material?code=' + this.formData.code
            // });
            this.actionIndex++
        },
        closeOutPicker() {
			this.activeIndex = []
            this.showOutPicker = false;
        },
        toggleOutOption(value) {
			if(this.activeIndex.includes(value.id)){
				this.activeIndex=this.activeIndex.filter(item=>item!=value.id)
			}else{
				this.activeIndex.push(value.id)
			}
			// this.arrActive = this
            const idx = this.selectedOutOption.indexOf(value)
            if (idx > -1) {
                // 已选中，取消
                this.selectedOutOption.splice(idx, 1)
            } else {
                // 未选中，添加
                this.selectedOutOption.push(value)
            }
        },
        confirmOut() {
			this.arrActive = [...this.activeIndex,...this.arrActive]
			this.activeIndex = []
            this.showOutPicker = false;
            // 多选，筛选所有选中的
            const selectedArr = this.outOptions.filter(item => this.selectedOutOption.includes(item.value));
            const uniqueArr = [];
            selectedArr.forEach(selected => {
                const exists = this.materialList.some(item => item.value === selected.value);
                if (!exists) {
                    this.materialList.push(selected);
                }
            });
            // 将选中的数据添加到materialList中，并根据重复id去重
            const materialList = this.selectedOutOption.reduce((acc, current) => {
				console.log(111,acc, current);
				 this.$set(this.imgListTwo, current.id, []);
				 // receive
				 this.$set(this.receive, current.id, {isShow:false});
                const existing = acc.find(item => item.id === current.id);
                if (!existing) {
                    current.num = 1;
                    acc.push(current);
                }
                return acc;
            }, []);
			this.materialList = [...this.materialList,...materialList]


            this.showMaterials = true;
            // 清空选择
            this.selectedOutOption = [];
        },
        selectOutOption(value) {
			console.log(value);
            // this.selectedOutOption = value;
			this.formData.supplier = value.name
			this.formData.supplierId = value.id
			
        },
		closeOutPickersupplier(){
			this.isShowsupplier = false
			this.formData.supplier = ''
			this.formData.supplierId = ''
		},
		confirmOutsupplier(){
			this.isShowsupplier = false
		},
        goToLook() {
            uni.navigateTo({
                url: `/pages/material/detail?data=${encodeURIComponent(JSON.stringify(this.formDataId))}`
            })
        },
        goToContinue() {
            this.actionIndex = 0;
            this.materialList = [];
            this.showMaterials = false;
            this.selectedOutOption = [];
            this.formParams = {};
            this.formData.supplier = ''
            this.formData.supplierId = ''
            this.formData.enterTime = timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss')
            this.annexName = ''
            this.imgList = []
            this.imgFile = []
            this.tempFile = []
            this.maxNum = 5,
                this.formData.contractPrice = ''
				this.imgListTwo = {}

        }
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}
	
::v-deep .uni-input-wrapper{
	// width: 406rpx;
	// border-bottom: 1rpx solid #dadbde;
	
}
::v-deep .uv-text__value{
	font-size: 30rpx !important;
}
::v-deep .choose-btn{
		font-size: 30rpx;
	}
.container {
    height: 100vh;
    background-color: #E7E7E7;
}

.steps {
    padding: 30rpx 0;
    background-color: #fff;
    margin-bottom: 20rpx;
}

.form-content {
    background-color: #fff;
}

.form-item {
    padding-left: 32rpx;
    height: 112rpx;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E7E7E7;
	.form-input{
		font-size: 30rpx;
		.input-text{
			font-size: 30rpx;
			color:#E7E7E7
		}
	}
	.label-text{
		font-size: 30rpx;
	}
	.choose-btn{
		font-size: 30rpx;
	}
    .form-padding{
		padding-left: 18rpx;
	}
    .imgfile {
        height: 80rpx;
        width: 80rpx;
        object-fit: contain;
        aspect-ratio: 1 / 1;
        margin-right: 8rpx;
    }
	.wrap__preview{
		position: relative;
	}
	.deletable{
		position: absolute;
		top: 0;
		right: 0;
		width: 28rpx;
		height: 28rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-bottom-left-radius: 100px;
		background-color: #373737;
	}

    .plus-icon {
        width: 80rpx;
        height: 80rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1rpx solid #E6EAF3;
        border-radius: 10rpx;
    }

    .form-label {
        width: 200rpx;
        margin-right: 32rpx;
    }

    .input-text {
        color: rgba(0, 0, 0, 0.75);
    }

    .input {
        border: 0;
    }
}

.materials-form {
    .selector {
        display: flex;
        align-items: center;
        padding-left: 32rpx;
        height: 112rpx;
        background-color: #fff;
        font-family: PingFang SC;
        font-size: 32rpx;
        font-weight: normal;
        margin-bottom: 20rpx;

        .selector-title {
            width: 162rpx;
            margin-right: 32rpx;
			font-size: 30rpx
        }

        .selector-content {
            flex: 1;
			font-size: 30rpx;
            color: rgba(29, 33, 41, 0.65);
        }
    }

    .materials {
        margin: 0 32rpx;
        background-color: #fff;
        border-radius: 20rpx;

        .materials-from {
            height: calc(100vh - 500rpx);
			background-color: #E7E7E7;
        }
		.empty{
			height: 1px;
			margin-top: 180rpx;
		}

        .materials-item {
            padding: 20rpx 20rpx 20rpx 30rpx;
            display: flex;
            align-items: center;
            // border-bottom: 1px solid #E7E7E7;
			background-color: #ffffff;
			margin-bottom: 20rpx;
        }

        .materials-title {
            height: 100rpx;
            line-height: 100rpx;
            padding-left: 40rpx;
            font-family: 思源黑体;
            font-size: 24rpx;
            font-weight: normal;
        }

        .materials-img {
            width: 120rpx;
            height: 120rpx;
        }

        .description {
            width: 220rpx;
            margin-left: 20rpx;
        }

        .materials-encoding {
            margin-bottom: 12rpx;
            font-family: 思源黑体;
            font-size: 28rpx;
            color: #333333;
        }

        .description-content {
            font-size: 24rpx;
            display: flex
        }

        .desc,
        .desc_cycle {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 80rpx;
            display: block;
        }

        .from-price-input {
            width: 150rpx;
            margin-left: 20rpx;
            text-align: -webkit-center;
        }

        .from-use-input {
            // width: 120rpx;
            // text-align: -webkit-center;
            margin: 0 auto;
        }

        .from-price-input-input {
            width: 120rpx;
            height: 1.2rem;
        }

        ::v-deep .uni-input-input {
            // text-align: ;
        }
		::v-deep .uv-input{
			padding: 0 !important;
		}

        .from-price-input-number {
            width: 100rpx;
        }
		
		.material-item{
			position: relative;
			width: 100%;
			// height: 40px;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-radius: 40rpx;
			margin-bottom: 20rpx;
			.delete-but{
				position: absolute;
				top: 20rpx;
				right: 30rpx;
				width: 124rpx;
				height: 72rpx;
				line-height: 72rpx;
				text-align: center;
				color: #F53F3F;
				background-color: #FFECE8;
				border-radius: 72rpx;
			}
			.item-box{
				display: flex;
				height: 48rpx;
				.title{
					width: 150rpx;
					text-align: right;
					margin-right: 20rpx;
				}
				.content-flex{
					display: flex;
					
					.uv-text{
						flex: 0;
					}
					
					.imgfile {
						height: 80rpx;
						width: 80rpx;
						object-fit: contain;
						aspect-ratio: 1 / 1;
						margin-right: 8rpx;
					}
					.wrap__preview{
						position: relative;
					}
					.deletable{
						position: absolute;
						top: 0;
						right: 0;
						width: 28rpx;
						height: 28rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						border-bottom-left-radius: 100px;
						background-color: #373737;
					}

					.plus-icon {
						width: 80rpx;
						height: 80rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						border: 1rpx solid #E6EAF3;
						border-radius: 10rpx;
					}
				}
				.content-input{
					width: 390rpx;
					border-bottom: 1rpx solid #dadbde;
					padding: 0 6rpx;
					::v-deep .uni-input-placeholder {
						// padding: 0 6rpx;
						font-size: 28rpx;
						color:rgb(192, 196, 204)
					}
						
					::v-deep .uni-input-input{
						color: rgb(48, 49, 51);
						    font-size: 14px;
					}
					
				}
			}
			
			.accessory{
				min-height: 100rpx;
				align-items: center;
			}
			.bottom-button{
				display: flex;
				margin-top: 30rpx;
				// align-items: center;
				// justify-content: space-between;
				.bottom-button-box{
					flex: 1;
				}
				.but{
					// width: 124rpx;
					// flex: 1;
					width: 100%;
					height: 72rpx;
					font-size: 30rpx;
					line-height: 72rpx;
					text-align: center;
					color: #165DFF;
					border-radius: 70rpx;
					background-color: #E8F3FF;
				}
			}
		}
    }



}

.management {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.succeed-img {
    margin-top: 148rpx;
    width: 240rpx;
    height: 220rpx;
}

.reminder {
    margin: 40rpx 0rpx;
    font-family: 思源黑体;
    font-size: 28rpx;
    font-weight: normal;

}

.but {
    width: 480rpx;
    height: 80rpx;
    font-family: 思源黑体;
    font-size: 28rpx;
    text-align: center;
    font-weight: normal;
    line-height: 80rpx;
    border-radius: 80rpx;
    border: 1px solid #235EFF;
}

.look-but {
    color: #235EFF;
    margin-bottom: 40rpx;
}

.continue-but {
    color: #FFFFFF;
    background-color: #235EFF;
}

/* 修改底部弹出层部分 */
.picker-container {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 100;
}

.picker-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.4);
}

.picker-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #FFFFFF;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
}

.picker-header {
    display: flex;
    height: 53px;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    border-bottom-width: 1px;
    border-bottom-color: #EEF2F9;
    margin-bottom: 30rpx;
}

.picker-title {
    font-size: 16px;
    color: #1D2129;
    font-weight: 400;
}

.picker-cancel,
.picker-confirm {
    font-size: 30rpx;
}

.picker-cancel {
    color: #86909C;
}

.picker-confirm {
    color: #165DFF;
}

.form-head {
    display: flex;
    flex-direction: row;
    margin: 0 23rpx;
    height: 56rpx;
    font-size: 24rpx;
    color: #FFFFFF;
    line-height: 56rpx;
    background-color: #4980FF;
}

.form-select {
    width: 88rpx;
    padding-left: 16rpx;
}

.form-encoding {
    width: 200rpx;
    padding-left: 16rpx;
}

.from-name {
    width: 180rpx;
    padding-left: 16rpx;
}

.from-specification {
    max-width: 120rpx;
    padding-left: 16rpx;
}

.form-encoding,
.from-name,
.from-specification {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
    max-width: 180rpx; // 按需调整
}

.picker-list {
    padding: 24rpx 0;
    padding-top: 0;
    max-height: 350rpx;
    margin-bottom: 12px;
    /* overflow: scroll; */
}

.picker-item {
    display: flex;
    height: 56rpx;
    flex-direction: row;
    /* justify-content: center; */
    align-items: center;
    padding: 0 16px;
	font-size: 30rpx;
}

.from-double {
    background: rgba(73, 128, 255, 0.06);
}

.management {
    align-items: center;
}

.succeed-img {
    margin-top: 148rpx;
    width: 240rpx;
    height: 220rpx;
}

.reminder {
    margin: 40rpx 0rpx;
    font-family: 思源黑体;
    font-size: 30rpx;
    font-weight: normal;

}

.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 94px;
    justify-content: center;
    align-items: center;
    padding: 10px 30px;
}

.next-button {
    display: flex;
    width: 315px;
    height: 44px;
    background-color: #E8F3FF;
    border-radius: 22px;
    justify-content: center;
    align-items: center;
	margin: 0 auto;
}

.button-text {
    font-size: 28rpx;
    color: #165DFF;
}

.minus {
    width: 22px;
    height: 22px;
    border-width: 1px;
    border-color: #E6E6E6;
    border-style: solid;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;
}

.input {
    padding: 0 10px;
}

.plus {
    width: 15px;
    height: 15px;
    background-color: #FF0000;
    border-radius: 50%;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;
}
/* 修改底部弹出层部分 */
		.picker-containers {
		  position: fixed;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  top: 0;
		  z-index: 11000;
		}
		
		.picker-masks {
		  position: absolute;
		  top: 0;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  background-color: rgba(0, 0, 0, 0.4);
		}
		
		.picker-contents {
		  position: absolute;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  height: 500rpx;
		  background-color: #FFFFFF;
		  border-top-left-radius: 16px;
		  border-top-right-radius: 16px;
		}
		
		.picker-headers {
		  display: flex;
		  height: 53px;
		  flex-direction: row;
		  justify-content: space-between;
		  align-items: center;
		  padding: 0 16px;
		  border-bottom-width: 1px;
		  border-bottom-color: #EEF2F9;
		  margin-bottom: 30rpx;
		}
		
		.picker-titles {
		  font-size: 16px;
		  color: #1D2129;
		  font-weight: 400;
		}
		
		.picker-cancels, .picker-confirms {
		  font-size: 16px;
		}
		
		.picker-cancels {
		  color: #86909C;
		}
		
		.picker-confirms {
		  color: #165DFF;
		}
		
		.picker-lists {
		  padding: 24rpx 0;
		  max-height: 350rpx;
		  /* overflow: scroll; */
		}
		
		.picker-items {
			display: flex;
		  height: 44px;
		  flex-direction: row;
		  justify-content: center;
		  align-items: center;
		  padding: 0 16px;
		  overflow: hidden;
		  white-space: nowrap;
		  text-overflow: ellipsis;
		}
		.selecteds{
			background-color: #E8F3FF;
		}
		.black-boxs{
			height: 50rpx;
		}
		.picker-items text {
		  font-size: 16px;
		  color: #1D2129;
		}
</style>
